<script setup>
import { profileGetService, profilePostAvatarService, profilePutAvatarRandomlyService, profilePutService } from '@/api/profile';
import { videoGetFavoriteVideo, videoGetLikeVideo, videoGetPublishedVideo } from '@/api/video';
import { videoCollectionsDeleteService, videoCollectionsGetService, videoCollectionsPostService, videoCollectionsPutService } from '@/api/video-collections';
import { useUserStore } from '@/stores';
import { throttle } from '@/utils/lodash';
import {
  UserFilled,
  Lollipop,
  VideoCamera,
  Star,
  Collection,
  FolderAdd,
  More,
  ArrowLeft
} from '@element-plus/icons-vue'
import { ref, reactive, watch } from 'vue'

const userStore = useUserStore();

/* 编辑资料 */
const editBioTextareaStyle = {
  "height": "120px"
}
const editProfileVisible = ref(false);

const profileModel = ref({
  'name': '',
  'bio': ''
});

const onClickProfileButton = async() => {
  try {
    const res = await profileGetService();
    const { name, avatarUrl, bio } = res.data.data;
    userStore.userBasicInfo.name = name;
    userStore.userBasicInfo.avatarUrl = avatarUrl;
    profileModel.value = { name, bio };
  } catch {
    profileModel.value.name = userStore.userBasicInfo?.name;
  }
  editProfileVisible.value = true;
}

const onSave = async() => {
  await profilePutService(profileModel.value);
}

/* 上传头像 */
const allowedAvatarExtensions = ['png', 'jpg', 'jpeg', 'gif'];
const allowedAvatarFileTypes = 'image/png, image/jpeg, image/gif';
const maxSizeMB = 2;
const maxFileSize = maxSizeMB * 1024 * 1024; // 转为字节

const beforeUploadAvatar = (file) => {
  const fileExtension = file.name.split('.').pop().toLowerCase();
  const isTypeValid = allowedAvatarExtensions.includes(fileExtension);
  if (!isTypeValid) {
    ElMessage.error(`仅支持 ${allowedAvatarExtensions.join(', ')} 格式的文件`);
    return false;
  }

  if (file.size > maxFileSize) {
    ElMessage.error(`文件大小不能超过 ${maxSizeMB}MB`);
    return false;
  }

  return true;
};

const uploadAvatar = async(options) => {
  const { file, onProgress, onError } = options;

  try {
    await profilePostAvatarService(file, onProgress);
    const url = URL.createObjectURL(file);
    userStore.userBasicInfo.avatarUrl = url;
  } catch (error) {
    onError(error);
  }
};

const updateAvatarRandomly = async () => {
  const url = (await profilePutAvatarRandomlyService()).data.data;
  userStore.userBasicInfo.avatarUrl = url;
}

/* 菜单项 */
const tabs = ['works', 'likes', 'favorites'];

const allTabStates = reactive(
  tabs.reduce((acc, tab) => {
    acc[tab] = {
      data: [],        // 该tab的数据列表
      lastMinId: null,          // 当前页码
      isLoading: false, // 是否正在首次加载
      isLoadingMore: false, // 是否正在加载更多
      isFinished: false,    // 是否已加载全部数据
    };
    return acc;
  }, {})
);

const activeTab = ref('works');
watch(activeTab, (newTab, oldTab) => {
  loadData();
}, { immediate: true });

async function loadData() {
  let dataList = null;
  let lastMinId = null;
  const tabState = allTabStates[activeTab.value];

  if (activeTab.value === 'works') {
    dataList = (await videoGetPublishedVideo(tabState.lastMinId)).data.data;
    lastMinId = dataList[dataList.length - 1].id;
  } else if (activeTab.value === 'likes') {
    dataList = (await videoGetLikeVideo(tabState.lastMinId)).data.data;
    lastMinId = dataList[dataList.length - 1].likeId;
  } else {
    dataList = (await videoCollectionsGetService(tabState.lastMinId)).data.data;
    lastMinId = dataList[dataList.length - 1].id;
  }

  tabState.lastMinId = lastMinId;
  tabState.data.push(...dataList);
}

/* 收藏夹 */
const collectionsDialogVisible = ref(false);
const collectionsDialogTitle = ref("新建收藏夹");
const collectionsModel = ref({
  name: '',
  isPublic: 0
})
const editingCollections = ref(null);

// 当点击创建收藏夹按钮
const onClickCreateCollections = () => {
  if (collectionsDialogTitle.value === "编辑收藏夹") {
    collectionsDialogTitle.value = "新建收藏夹";
    collectionsModel.value.name = '';
    collectionsModel.value.isPublic = 0;
  }

  collectionsDialogVisible.value = true
}

// 创建收藏夹
const createCollections = async () => {
  const modelData = collectionsModel.value;
  const data = (await videoCollectionsPostService(modelData)).data.data;
  modelData['id'] = data;
  modelData['itemCount'] = 0;
  allTabStates['favorites'].data.push(modelData);
  
  collectionsDialogVisible.value = false;
}

// 当点击编辑收藏夹按钮
const onClickEditCollections = (collections) => {
  collectionsDialogTitle.value = "编辑收藏夹";
  collectionsModel.value.name = collections.name;
  collectionsModel.value.isPublic = collections.isPublic;
  editingCollections.value = collections;

  collectionsDialogVisible.value = true;
}

// 编辑收藏夹
const editCollections = async () => {
  const id = editingCollections.value.id;
  const modelData = collectionsModel.value;
  await videoCollectionsPutService(id, modelData);
  const collections = allTabStates['favorites'].data.find(item => item.id === id);
  collections['name'] = modelData.name;
  collections['isPublic'] = modelData.isPublic;

  collectionsDialogVisible.value = false;
}

// 删除收藏夹
const deleteCollections = async (id) => {
  await ElMessageBox.confirm('你确定要删除该收藏夹么', '温馨提示', {
    type: 'warning',
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  })

  await videoCollectionsDeleteService(id);
  const index = allTabStates['favorites'].data.findIndex(item => item.id === id);
  if (index !== -1) {
    allTabStates['favorites'].data.splice(index, 1);
  }
}

// 点击收藏夹
const currentCollections = ref(null);
const onClickCollections = (collections) => {
  currentCollections.value = collections;
}

/* 点击视频项 */
const showVideoViewer = ref(false);
const clickedVideoId = ref(null);
const currentIdx = ref(null);

function onClickVideoItem(index, id) {
  clickedVideoId.value = id;
  showVideoViewer.value = true;
  currentIdx.value = index;
}

function handleViewerUp() {
  const tabState = allTabStates[activeTab.value];

  if (currentIdx.value > 0) {
    currentIdx.value--;
    clickedVideoId.value = tabState.data[currentIdx.value].id || tabState.data[currentIdx.value].videoId;
  }
}

function handleViewerDown() {
  const tabState = allTabStates[activeTab.value];

  if (currentIdx.value < tabState.data.length -1) {
    currentIdx.value++;
    clickedVideoId.value = tabState.data[currentIdx.value].id || tabState.data[currentIdx.value].videoId;
  }
}

</script>

<template>
  <el-container class="self-container">
    <el-header class="self-header">
      <el-avatar class="user-avatar" :src="userStore.userBasicInfo?.avatarUrl" :icon="UserFilled" fit="fill"></el-avatar>
      <div class="self-header-right">
        <span class="user-name">{{ userStore.userBasicInfo?.name }}</span>
        <el-button class="edit-profile-button" @click="onClickProfileButton" round>编辑资料</el-button>
        
        <el-dialog class="edit-dialog" title="编辑资料" v-model="editProfileVisible">
          <el-container class="edit-profile-container">
            <el-header class="edit-profile-header">
              <el-upload class="edit-profile-user-avatar-warpper" :http-request="uploadAvatar" :accept="allowedAvatarFileTypes" :before-upload="beforeUploadAvatar">
                <el-avatar class="edit-profile-user-avatar" :src="userStore.userBasicInfo?.avatarUrl" :icon="UserFilled" fit="fill"></el-avatar>
              </el-upload>
            </el-header>

            <el-main class="edit-profile-main">
              <el-form label-position="top">
                <el-form-item label="名字">
                  <el-input v-model="profileModel.name"></el-input>
                </el-form-item>
                <el-form-item label="简介">
                  <el-input v-model="profileModel.bio" :input-style="editBioTextareaStyle" resize="none" type="textarea"></el-input>
                </el-form-item>
              </el-form>
            </el-main>

            <el-footer>
              <el-button style="width: 100%;" type="danger" @click="onSave">保存</el-button>
            </el-footer>
          </el-container>
        </el-dialog>
      </div>
    </el-header>

    <el-main class="profile-main">
      <el-tabs v-model="activeTab" class="profile-tabs">
        <el-tab-pane name="works">
          <template #label>
            <span class="tab-label">
              <el-icon><VideoCamera /></el-icon>
              <span>作品 {{ allTabStates['works'].data.length }}</span>
            </span>
          </template>
          <div class="video-grid">
            <div v-for="(video, index) in allTabStates['works'].data" :key="video.id" class="video-card" @click="onClickVideoItem(index, video.id)">
              <div class="video-thumb" :style="{ backgroundImage: `url(${video.coverUrl})` }">
                <div class="video-stats">
                  <span><el-icon><VideoCamera /></el-icon> {{ video.views }}</span>
                  <span>
                    <el-icon>
                      <Like />
                    </el-icon> {{ video.likes }}
                  </span>
                </div>
              </div>
              <div class="video-title">{{ video.description }}</div>
            </div>
          </div>
        </el-tab-pane>
        
        <el-tab-pane name="likes">
          <template #label>
            <span class="tab-label">
              <el-icon>
                <Like />
              </el-icon>
              <span>喜欢 {{ allTabStates['likes'].data.length }}</span>
            </span>
          </template>
          <div class="video-grid">
            <div v-for="(video, index) in allTabStates['likes'].data" :key="video.likeId" class="video-card" @click="onClickVideoItem(index, video.videoId)">
              <div class="video-thumb" :style="{ backgroundImage: `url(${video.coverUrl})` }">
                <div class="video-stats">
                  <span>
                    <el-icon>
                      <Like />
                    </el-icon> {{ video.likes }}
                  </span>
                </div>
              </div>
              <div class="video-info">
                <div class="video-title">{{ video.description }}</div>
                <div class="video-author">@{{ video.creatorName }}</div>
              </div>
            </div>
          </div>
        </el-tab-pane>
        
        <el-tab-pane name="favorites">
          <template #label>
            <span class="tab-label">
              <el-icon><Star /></el-icon>
              <span>收藏 {{ allTabStates['favorites'].data.length }}</span>
            </span>
          </template>
          <div v-if="!currentCollections" style="display: flex; align-items: center; justify-content: right;">
            <el-button style="border-radius: 10px; color: white;" :icon="FolderAdd" @click="onClickCreateCollections">新建收藏夹</el-button>
          </div>
          <div v-else style="display: flex; align-items: center; justify-content: left;">
            <el-button style="border-radius: 10px; color: white;" :icon="ArrowLeft" @click="currentCollections = null">{{ currentCollections.name }}</el-button>
          </div>
          <div :class="currentCollections ? 'video-grid' : 'collection-grid'">
            <div v-if="!currentCollections" v-for="collections in allTabStates['favorites'].data" :key="collections.id" class="collection-card">
              <div @click="onClickCollections(collections)" class="collection-cover" :style="{ backgroundImage: `url(${collections.cover})` }">
                <div class="collection-count">{{ collections.itemCount }} 个视频</div>
              </div>
              <div class="collection-title">{{ collections.name }}</div>
              <el-popover
                placement="bottom"
              >
                <template #reference>
                  <el-icon class="collection-more"><More /></el-icon>
                </template>
                <template #default>
                  <div class="collection-more-container">
                    <div class="collection-more-item" @click="onClickEditCollections(collections)">编辑收藏夹</div>
                    <div class="collection-more-item" @click="deleteCollections(collections.id)">删除收藏夹</div>
                  </div>
                </template>
              </el-popover>
            </div>
            <div v-else v-for="(video, index) in allTabStates['likes'].data" :key="video.likeId" class="video-card" @click="onClickVideoItem(index, video.videoId)">
              <div class="video-thumb" :style="{ backgroundImage: `url(${video.coverUrl})` }">
                <div class="video-stats">
                  <span>
                    <el-icon>
                      <Like />
                    </el-icon> {{ video.likes }}
                  </span>
                </div>
              </div>
              <div class="video-info">
                <div class="video-title">{{ video.description }}</div>
                <div class="video-author">@{{ video.creatorName }}</div>
              </div>
            </div>
          </div>
          <el-dialog :title="collectionsDialogTitle" v-model="collectionsDialogVisible" width="25%">
            <el-form style="padding: 10%;">
              <el-form-item label="收藏夹名">
                <el-input v-model="collectionsModel.name"></el-input>OtherInfo.log
              </el-form-item>
              <el-form-item label="是否公开">
                <el-switch
                  v-model="collectionsModel.isPublic"
                  active-value="1"
                  inactive-value="0"
                />
              </el-form-item>
              <el-button style="width: 100%; margin-top: 10px;" @click="(collectionsDialogTitle === '新建收藏夹' ? createCollections : editCollections)()">确认</el-button>
            </el-form>
          </el-dialog>
        </el-tab-pane>
      </el-tabs>
    </el-main>
  </el-container>
  <yx-video-viewer v-model="showVideoViewer" @up="handleViewerUp" @down="handleViewerDown" :video-id="clickedVideoId" />
</template>

<style lang="scss" scoped>
.self-container {
  box-sizing: border-box;
  height: 100%;
  padding: 1vw;
  border-radius: 5px;
  background: linear-gradient(to top, #060716, #ffffff, #060716);

  .self-header {
    display: flex;
    height: 100px;
    padding: 20px 0;

    .user-avatar {
      height: 100%;
      width: auto;
      margin-right: 30px;
      aspect-ratio: 1/1;
      border: 3px solid rgba(255, 255, 255, 0.1);
    }

    .self-header-right {
      display: flex;
      flex: 1;
      align-items: center;
      justify-content: space-between;

      .user-name {
        font-size: 24px;
        font-weight: bold;
        color: #fff;
        text-shadow: 0 0 10px rgba(255, 255, 255, 0.3);
      }

      .edit-profile-button {
        align-self: flex-end;
        background: rgba(255, 255, 255, 0.1);
        color: #fff;
        border: none;
        font-weight: bold;
        transition: all 0.3s ease;
        
        &:hover {
          background: rgba(255, 255, 255, 0.2);
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
        }
      }
    }
  } 

  .profile-main {
    height: calc(100% - 140px);
    padding: 20px 0;
    
    .profile-tabs {
      height: 100%;
      user-select: none;
      
      :deep(.el-tabs__header) {
        margin: 0 0 20px;
      }

      :deep(.el-tabs__content) {
        flex: 1;
        overflow-y: auto;
        padding: 10px;
        
        // 自定义滚动条
        &::-webkit-scrollbar {
          width: 6px;
        }
        
        &::-webkit-scrollbar-track {
          background: rgba(255, 255, 255, 0.1);
          border-radius: 3px;
        }
        
        &::-webkit-scrollbar-thumb {
          background: rgba(255, 255, 255, 0.3);
          border-radius: 3px;
          
          &:hover {
            background: rgba(255, 255, 255, 0.5);
          }
        }
      }
      
      :deep(.el-tabs__nav-wrap::after) {
        background-color: rgba(255, 255, 255, 0.1);
      }
      
      :deep(.el-tabs__active-bar) {
        background: linear-gradient(to right, #4361ee, #3a0ca3);
        height: 3px;
        border-radius: 3px;
      }
      
      :deep(.el-tabs__item) {
        color: rgba(255, 255, 255, 0.6);
        font-size: 16px;
        font-weight: bold;
        padding: 0 20px;
        height: 40px;
        transition: all 0.3s ease;
        
        &:hover {
          color: #fff;
        }
        
        &.is-active {
          color: #fff;
        }
      }
      
      .tab-label {
        display: flex;
        align-items: center;
        
        .el-icon {
          margin-right: 8px;
          font-size: 18px;
        }
      }
    }
    
    .video-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
      gap: 20px;
      padding: 10px 0;
      user-select: none;
      
      .video-card {
        background: rgba(255, 255, 255, 0.05);
        border-radius: 12px;
        overflow: hidden;
        transition: all 0.3s ease;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        cursor: pointer;
        
        &:hover {
          transform: translateY(-5px);
          box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2);
          background: rgba(255, 255, 255, 0.08);
        }
        
        .video-thumb {
          position: relative;
          width: 100%;
          padding-top: 133.33%; /* 3:4 比例 */
          background-size: cover;
          background-position: center;
          
          .video-stats {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            display: flex;
            justify-content: space-between;
            padding: 8px 10px;
            background: linear-gradient(to top, rgba(0,0,0,0.7), transparent);
            color: #fff;
            font-size: 12px;
            
            span {
              display: flex;
              align-items: center;
              
              .el-icon {
                margin-right: 4px;
                font-size: 14px;
              }
            }
          }
        }
        
        .video-title {
          padding: 12px;
          font-size: 14px;
          color: #fff;
          font-weight: 500;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }
        
        .video-info {
          padding: 12px;
          
          .video-title {
            padding: 0 0 6px;
            font-size: 14px;
          }
          
          .video-author {
            font-size: 12px;
            color: rgba(255, 255, 255, 0.6);
          }
        }
      }
    }
    
    .collection-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
      gap: 25px;
      padding: 10px 0;
      
      .collection-card {
        position: relative;
        background: rgba(255, 255, 255, 0.05);
        border-radius: 12px;
        overflow: hidden;
        transition: all 0.3s ease;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        cursor: pointer;
        
        &:hover {
          transform: translateY(-5px);
          box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2);
          background: rgba(255, 255, 255, 0.08);
        }
        
        .collection-cover {
          position: relative;
          width: 100%;
          padding-top: 100%; /* 1:1 比例 */
          background-size: cover;
          background-position: center;
          
          .collection-count {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            padding: 8px 10px;
            background: linear-gradient(to top, rgba(0,0,0,0.7), transparent);
            color: #fff;
            font-size: 12px;
            text-align: center;
          }
        }
        
        .collection-title {
          padding: 15px;
          font-size: 16px;
          color: #fff;
          font-weight: bold;
          text-align: center;
        }

        .collection-more {
          font-size: 1.2em;
          position: absolute;
          top: 5px;
          right: 5px;
          
          &:hover {
            color: black;
            transition: color 0.3s ease;
          }
        }
      }
    }
  }
}

.collection-more-container {
  text-align: center;
  font-size: 1.2em;
}

.collection-more-item {
  padding: 4px 0px;
  cursor: pointer;

  &:hover {
    color: white;
    background-color: black;
  }
}

:deep(.edit-dialog) {
  width: 50vw;

  @media (min-width: 768px) {
    width: 32vw;
  }

  @media (min-width: 1024px) {
    width: 22vw;
  }
}

.edit-profile-container {
  .edit-profile-header {
    height: 80px;
    display: flex;
    justify-content: center;
    align-items: center;

    .edit-profile-user-avatar-warpper {
      height: 100%;
      width: auto;
      aspect-ratio: 1/1;

      ::v-deep(.el-upload) {
        height: 100%;
        width: 100%;
        .edit-profile-user-avatar {
          height: 100%;
          width: 100%;
        }
      }
    }
  }

  .edit-profile-main {
    padding: 0 20px;
  }
}
</style>